var pwd_tmp = "";
var lock = false;

$(document).ready(reset);

/**
 * 初始化函数
 *
 * 包括jQuery事件的绑定等
 * @return void
 */
function reset() {
    if (getCookie("uname_base64") !== "") {
        var uname = window.atob(getCookie("uname_base64"));
        $("#username").val(uname);
        $("#ico").attr("alt", uname);
        $("#ico").attr("src", "./static/images/" + uname + ".png");
    }
    $("#login").click(login);
    $("#password").focus(pwdFocus);
    $("#password").blur(pwdBlur);
}

function pwdFocus() {
    pwd_tmp = $("#password").val();
    $("#password").val("");
}

function pwdBlur() {
    if ($("#password").val() === "")
        $("#password").val(pwd_tmp);
}

/**
 * 显示
 *
 * 在状态栏显示当前情况
 * @return void
 */
function echo(message, color) {
    var html = "<p style=\"color:" + color + "\">" + message + "</p>";
    $("#echo").html(html);
}

/**
 * 请求失败处理函数
 *
 * 匹配错误原因并显示
 * @return void
 */
function dealFail(reason) {
    switch (reason) {
        case "need_uname&pwd":
            echo("内部错误(服务器未收到用户名或密码)", "red");
            break;
        case "no_key":
            echo("内部错误(密码校验参数不存在)", "red");
            break;
        case "wrong":
            echo("用户名或密码错误", "red");
            break;
        case "no_login":
            echo("内部错误(登录失败)", "red");
            break;
        case "please_login_again":
            echo("请重新登录", "red");
            break;
        default:
            echo("内部错误(未知错误)", "red");
    }
}

/**
 * 登录函数-第一步
 *
 * 检查用户名密码是否输入，发送获取key请求
 * @return loginS2()
 */
function login() {
    if (lock)
        return;
    lock = true;
    if ($("#username").val() === "") {
        echo("用户名不能为空", "red");
        lock = false;
        return;
    }
    if ($("#password").val() === "") {
        echo("密码不能为空", "red");
        lock = false;
        return;
    }
    $.post("./api.php",
        {
            action: "getkey"
        }, loginS2);
    echo("正在获取密码校验参数...", "green");
}

/**
 * 登录函数-第二步
 *
 * 处理获取key请求，发送校验密码请求
 * @return loginS3()
 */
function loginS2(data, status) {
    if (status !== "success") { //请求失败处理（网络层面）
        echo("请求失败，请检查网络连接", "yellow");
        lock = false;
        return;
    }
    var response = $.parseJSON(data);
    if (response.status !== "success") { //请求失败处理（服务器层面）
        if (response.status === "fail") {
            var reason = response.reason;
            dealFail(reason);
        } else if (response.status === "error") {
            echo("服务器内部错误", "red");
        } else {
            echo("解析服务器响应失败", "red");
        }
        lock = false;
        return;
    }
    var key = response.context;
    var uname = $("#username").val();
    var pwd = $("#password").val();
    var pwd_encode = md5(pwd + key);
    $.post("./api.php",
        {
            action: "loginon",
            uname: uname,
            pwd: pwd_encode
        }, loginS3);
    echo("正在校验密码...", "green");
}

/**
 * 登录函数-第三步
 *
 * 处理校验密码请求，发送获取密钥请求
 * @return loginS4()
 */
function loginS3(data, status) {
    if (status !== "success") { //请求失败处理（网络层面）
        echo("请求失败，请检查网络连接", "yellow");
        lock = false;
        return;
    }
    var response = $.parseJSON(data);
    if (response.status !== "success") { //请求失败处理（服务器层面）
        if (response.status === "fail") {
            var reason = response.reason;
            dealFail(reason);
        } else if (response.status === "error") {
            echo("服务器内部错误", "red");
        } else {
            echo("未知错误", "red");
        }
        lock = false;
        return;
    }
    $.post("./api.php",
        {
            action: "getaes"
        }, loginS4);
    echo("密码校验成功，正在获取传输密钥...", "green");
}

/**
 * 登录函数-第四步
 *
 * 处理获取密钥请求，写入localStorage，并刷新页面
 * @return refresh
 */
function loginS4(data, status) {
    if (status !== "success") { //请求失败处理（网络层面）
        echo("请求失败，请检查网络连接", "yellow");
        lock = false;
        return;
    }
    var response = $.parseJSON(data);
    if (response.status !== "success") { //请求失败处理（服务器层面）
        if (response.status === "fail") {
            var reason = response.reason;
            dealFail(reason);
        } else if (response.status === "error") {
            echo("服务器内部错误", "red");
        } else {
            echo("未知错误", "red");
        }
        lock = false;
        return;
    }
    var aes_encrypt = response.context;
    var pwd = $("#password").val();
    var aes_tmp = md5(pwd).substr(0, 16);
    var aes = decrypt(aes_encrypt, aes_tmp);
    localStorage.setItem("aes_key", aes); //储存aes密钥
    var uname = $("#username").val();
    var uname_base64 = window.btoa(uname);
    setCookie("uname_base64", uname_base64, 7);
    echo("获取密钥成功，正在跳转...", "green");
    lock = false;
    location.replace(location.href);
}

document.onkeypress = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if (e && e.keyCode == 13) { //enter
        login();
    }
};
